package com.goatyyc.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.goatyyc.common.utils.PageUtils;
import com.goatyyc.common.utils.Query;

import com.goatyyc.product.dao.CategoryDao;
import com.goatyyc.product.entity.CategoryEntity;
import com.goatyyc.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entityList = baseMapper.selectList(null);
        // 组装成树状 todo
        // 1.挑出所有一级分类
        List<CategoryEntity> levelOneList = entityList.stream().filter(categoryEntity -> 
            categoryEntity.getParentCid() == 0
        )
                // 为每个菜单设置子菜单
                .map(menu -> {
                    menu.setChildren(getChildren(menu,entityList));
                    return menu;
                }).sorted((menu1,menu2)->{
                    return (menu1.getSort()==null ? 0 : menu1.getSort()) - (menu2.getSort()==null ? 0 : menu2.getSort());
                }).collect(Collectors.toList());
        // 2.为每个分类设置子分类
        
        return levelOneList;
    }

    /**
     * 递归获取子菜单
     * @return
     * @param root
     * @param all
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter((menu) ->
                menu.getParentCid().equals(root.getCatId())
        )
                // 为每个菜单设置子菜单
                .map((menu)->{
                    menu.setChildren(getChildren(menu,all));
                    return menu;
                })
                // 排序
                .sorted((menu1,menu2)->{
                    return (menu1.getSort()==null ? 0 : menu1.getSort()) - (menu2.getSort()==null ? 0 : menu2.getSort());
                })
                // 收集成list
                .collect(Collectors.toList());

        return children;
    }

}